<?php

class User extends CActiveRecord
{
	const STATUS_NOACTIVE=0;
	const STATUS_ACTIVE=1;
	const STATUS_BANED=-1;
	
	/**
	 * The followings are the available columns in table 'users':
	 * @var integer $id
	 * @var string $username
	 * @var string $password
	 * @var string $email
	 * @var string $activkey
	 * @var integer $createtime
	 * @var integer $lastvisit
	 * @var integer $superuser
	 * @var integer $status
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return Yii::app()->getModule('user')->tableUsers;
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		
		return ((Yii::app()->getModule('user')->isAdmin())?array(
			#array('username, password, email', 'required'),
			array('username', 'length', 'max'=>128, 'min' => 3,'message' => UserModule::t("Incorrect name (length between 3 and 128 characters).")),
			array('password', 'length', 'max'=>128, 'min' => 4,'message' => UserModule::t("Incorrect password (minimal length 4 symbols).")),
			array('email', 'email'),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
			array('status', 'in', 'range'=>array(self::STATUS_NOACTIVE,self::STATUS_ACTIVE,self::STATUS_BANED)),
			array('superuser', 'in', 'range'=>array(0,1)),
			array('username, email, createtime, lastvisit, superuser, status', 'required'),
			array('createtime, lastvisit, superuser, status', 'numerical', 'integerOnly'=>true),
		):((Yii::app()->user->id==$this->id)?array(
			array('username, email', 'required'),
			array('username', 'length', 'max'=>128, 'min' => 3,'message' => UserModule::t("Incorrect username (length between 3 and 128 characters).")),
			array('email', 'email'),
			array('email', 'unique', 'message' => UserModule::t("This user's email address already exists.")),
		):array()));
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		$relations = array(
			'profile'=>array(self::HAS_ONE, 'Profile', 'user_id'),
		);
		if (isset(Yii::app()->getModule('user')->relations)) $relations = array_merge($relations,Yii::app()->getModule('user')->relations);
		return $relations;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'username'=>UserModule::t('name'),
			'password'=>UserModule::t('password'),
			'verifyPassword'=>UserModule::t('Retype Password'),
			'email'=>UserModule::t('E-mail'),
			'verifyCode'=>UserModule::t('Verification Code'),
			'id' => UserModule::t('Id'),
			'activkey' => UserModule::t('activation key'),
			'createtime' => UserModule::t('Registration date'),
			'lastvisit' => UserModule::t('Last visit'),
			'superuser' => UserModule::t('Superuser'),
			'status' => UserModule::t('Status'),
		);
	}
	
	public function scopes()
    {
        return array(
            'active'=>array(
                'condition'=>'status='.self::STATUS_ACTIVE,
            ),
            'notactvie'=>array(
                'condition'=>'status='.self::STATUS_NOACTIVE,
            ),
            'banned'=>array(
                'condition'=>'status='.self::STATUS_BANED,
            ),
            'superuser'=>array(
                'condition'=>'superuser=1',
            ),
            'notsafe'=>array(
            	'select' => 'id, username, password, email, activkey, createtime, lastvisit, superuser, status',
            ),
        );
    }
	
	public function defaultScope()
    {
        return array(
            'select' => 'id, username, email, createtime, lastvisit, superuser, status',
        );
    }

    public function getProfileUrl()
    {
        return Yii::app()->urlManager->createUrl('/user/user/view', array('id'=>$this->id));
    }

    /*
     * Generates random password.
     * @return string password
     */
    private static function _generatePassword($maxlen = 8)
    {
        $result = '';

        for($i=0; $i < $maxlen; $i++) {
            $d = mt_rand(1,30) % 3;
            if ($d == 2)
                $result .= chr(mt_rand(0x41,0x5A)); // A-Z
            elseif ($d == 1)
                $result .= chr(mt_rand(0x61,0x7A)); // a-z
            else
                $result .= chr(mt_rand(0x30,0x39)); // 0-9
        }
        return $result;
    }

    /*
     * Returns user with specified email
     * If no user with email registered then register a new user with @username
     *
     * @return User model or null if can`t create (for example: invalid input)
     */
    public static function getUser($email, $username = null, $login = false)
    {
        $validator = new CEmailValidator;
        if (!$validator->validateValue($email)) {
            return null;
        }

        $user = User::model()->find('email=:email', array(':email'=>$email));
        if ($user == null) {
            $user = new User;
            $password = self::_generatePassword();

            $user->email = $email;
            $user->username = $username;
            $user->activkey = UserModule::encrypting(microtime().$password);
			$user->password = UserModule::encrypting($password);
			$user->createtime = time();
			$user->lastvisit = ($login) ? time() : 0;
			$user->superuser = 0;
			$user->status = User::STATUS_NOACTIVE;
            if ($user->save()) {
                $activationUrl = Yii::app()->getRequest()->getHostInfo().Yii::app()->urlManager->createUrl('/user/activation/activation',
                                              array("activkey" => $user->activkey, "email" => $user->email));
                $setPasswordUrl = Yii::app()->getRequest()->getHostInfo().Yii::app()->urlManager->createUrl(implode(Yii::app()->getModule('user')->recoveryUrl),
                                              array("activkey" => $user->activkey, "email" => $user->email));
				MailNotificationHelper::userRegistrationCompleted($user->email, array('email'=>$user->email,
                                                  'setPasswordUrl'=>$setPasswordUrl, 'activationUrl'=>$activationUrl));
            }

            $profile = new Profile;
            $profile->regMode = true;
            $profile->user_id = $user->id;
            $profile->save();

            if ($login == true) { // automaticaly log in as user
                $identity=new UserIdentity($email, $password);
                $identity->authenticate();
            }
        }
        return $user;
    }
	
	public static function itemAlias($type,$code=NULL) {
		$_items = array(
			'UserStatus' => array(
				self::STATUS_NOACTIVE => UserModule::t('Not active'),
				self::STATUS_ACTIVE => UserModule::t('Active'),
				self::STATUS_BANED => UserModule::t('Banned'),
			),
			'AdminStatus' => array(
				'0' => UserModule::t('No'),
				'1' => UserModule::t('Yes'),
			),
		);
		if (isset($code))
			return isset($_items[$type][$code]) ? $_items[$type][$code] : false;
		else
			return isset($_items[$type]) ? $_items[$type] : false;
	}
}
